package com.netty.encodedecode.protol;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

/**
 * @auther: cc.ly
 * @date: 2019/1/12/012
 */

public class ServerHandler extends SimpleChannelInboundHandler<PersonProtol> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress().toString() + "  connect.");
        PersonProtol p = new PersonProtol();
        String content = "Netty学习.";
        p.setContent(content.getBytes());
        p.setLength(content.getBytes().length);
        ctx.channel().writeAndFlush(p);
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, PersonProtol msg) throws Exception {
        System.out.println(new String(msg.getContent(), Charset.forName("utf-8")));
        //ctx.channel().writeAndFlush(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + " 下线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
